#
# @lc app=leetcode.cn id=701 lang=python
#
# [701] 二叉搜索树中的插入操作
#

# @lc code=start
# Definition for a binary tree node.
class TreeNode(object):
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right
class Solution(object):
    def insertIntoBST(self, root, val):
        """
        :type root: Optional[TreeNode]
        :type val: int
        :rtype: Optional[TreeNode]
        """
        self.val = val
        if root is None:
            return TreeNode(self.val)
        self.loop(root)
        return root

    def loop(self, node):
        if node is None:
            node = TreeNode(self.val)
            return node

        if node.val > self.val:
            node.left = self.loop(node.left)
        elif node.val < self.val:
            node.right = self.loop(node.right)

        return node
        
# @lc code=end

